<template>
  <div class="resource-management">
    <div class="page-header">
      <h2>教育资源管理</h2>
      <el-button type="primary" @click="handleAdd">
        新增资源
      </el-button>
    </div>

    <el-card class="table-card">
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="标题">
            <el-input
              v-model="searchForm.title"
              placeholder="请输入资源标题"
              clearable
            />
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="searchForm.type" placeholder="请选择资源类型" clearable>
              <el-option label="文章" value="ARTICLE" />
              <el-option label="视频" value="VIDEO" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="type" label="类型">
          <template #default="{ row }">
            <el-tag :type="row.type === 'ARTICLE' ? 'success' : 'warning'">
              {{ row.type === 'ARTICLE' ? '文章' : '视频' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="summary" label="简介" :show-overflow-tooltip="true" />
        <el-table-column prop="author" label="作者" />
        <el-table-column prop="viewCount" label="浏览量" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button 
              type="primary" 
              link 
              @click="handleStatusChange(row)"
            >
              {{ row.status === 1 ? '下架' : '发布' }}
            </el-button>
            <el-button 
              type="danger" 
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const router = useRouter()
const tableData = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = ref({
  title: '',
  type: ''
})

// 分页信息
const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})

// 获取资源列表
const fetchResources = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.value.current,
      size: pagination.value.size,
      ...searchForm.value
    }
    const { data } = await request.get('/admin/resource/list', { params })
    tableData.value = data.records
    pagination.value.total = data.total
  } catch (error) {
    console.error('Error fetching resources:', error)
    ElMessage.error('获取资源列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  fetchResources()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    title: '',
    type: ''
  }
  handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.value.size = val
  fetchResources()
}

const handleCurrentChange = (val) => {
  pagination.value.current = val
  fetchResources()
}

// 新增资源
const handleAdd = () => {
  router.push('/admin/resources/create')
}

// 编辑资源
const handleEdit = (row) => {
  router.push(`/admin/resources/edit/${row.id}`)
}

// 修改资源状态
const handleStatusChange = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '下架' : '发布'}该资源吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await request.put(`/admin/resource/${row.id}/status`, {
      status: row.status === 1 ? 0 : 1
    })
    ElMessage.success('操作成功')
    fetchResources()
  } catch (error) {
    console.error('Error changing resource status:', error)
    ElMessage.error('操作失败')
  }
}

// 删除资源
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该资源吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await request.delete(`/admin/resource/${row.id}`)
    ElMessage.success('删除成功')
    fetchResources()
  } catch (error) {
    console.error('Error deleting resource:', error)
    ElMessage.error('删除失败')
  }
}

onMounted(() => {
  fetchResources()
})
</script>

<style scoped>
.resource-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.search-area {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 